package fuzion24.device.vulnerability.test;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.afollestad.materialdialogs.MaterialDialog;

import java.util.ArrayList;
import java.util.List;

import fuzion24.device.vulnerability.vulnerabilities.VulnerabilityOrganizer;
import fuzion24.device.vulnerability.vulnerabilities.VulnerabilityTest;

public class VulnerabilityTestRunner extends AsyncTask<Void, Integer, List<VulnerabilityTestResult>> {

    private final Boolean mShowWaitDiaglog;
    private MaterialDialog mProgressDialog;
    private final ResultsCallback mCustomCallback;
    private final Context mCtx;
    private List<VulnerabilityTest> tests;

    private static final String TAG = "VULN_TEST";

    public VulnerabilityTestRunner(Context actv, Boolean showScanDialog, ResultsCallback callback) {
        mCtx = actv;
        mShowWaitDiaglog = showScanDialog;
        mCustomCallback = callback;
        tests = VulnerabilityOrganizer.getTests(mCtx);
    }

    @Override
    protected void onPreExecute() {
        if (mShowWaitDiaglog) {
            mProgressDialog = new MaterialDialog.Builder(mCtx)
                .title("Device Vulnerability Checker")
                .content("Checking device for publicly known vulnerabilities")
                .cancelable(false)
                .progress(false, tests.size())
                .show();
        }
    }

    @Override
    protected List<VulnerabilityTestResult> doInBackground(Void... params) {
        Log.d(TAG, "Async execute called!!!!");

        List<VulnerabilityTestResult> results = new ArrayList<>();

        for (int i = 0; i < tests.size(); i++) {
            mProgressDialog.setProgress(i);

            VulnerabilityTest test = tests.get(i);
            Log.d(TAG, "Running test: " + test.getCVEorID());
            Exception x = null;
            boolean isVuln = false;
            try {
                isVuln = test.isVulnerable(mCtx);
                Log.d(TAG, test.getCVEorID() + "  isVulnerable: " + isVuln);

            } catch (Exception e) {
                e.printStackTrace();
                Log.d(TAG, test.getCVEorID() + "  failed with: " + e.getMessage());
                x = e;
            }
            results.add(new VulnerabilityTestResult(test, isVuln, x));
        }

        return results;
    }

    @Override
    protected void onPostExecute(List<VulnerabilityTestResult> vulnerabilityResults) {
        super.onPostExecute(vulnerabilityResults);
        if (mCustomCallback != null)
            mCustomCallback.finished(vulnerabilityResults);

        if (mShowWaitDiaglog)
            mProgressDialog.dismiss();
    }

}
